package com.wang.experiment.experiment3.booksystem;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wr
 * @date 2021/10/25 9:10
 */
public class BookManager {
    /**
     * 存储书的容器
     */
    private List<Book> bookList;
    /**
     * 使用书籍唯一id查找书
     */
    private Map<String, Book> idBook;
    /**
     * 使用书名查找书的map
     * book可重名
     */
    private Map<String, List<Book>> nameBook;

    public BookManager() {
        bookList = new ArrayList<>();
        idBook = new HashMap<>();
        nameBook = new HashMap<>();
    }

    public List<Book> getBookList() {
        return bookList;
    }

    //添加书籍
    public void addBook(Book book) {
        while (idBook.containsKey(book.getId())) {
            //避免uuid冲突
            book.changeId();
        }
        bookList.add(book);
        addBookIndex(book);
    }

    //通过书籍id获取书籍
    public Book getBookById(String id) {
        return idBook.get(id);
    }

    //通过书名获取书籍列表
    public List<Book> getBooksByName(String name) {
        //无数据时返回空列表,与 showBookData() 兼容
        return nameBook.containsKey(name) ? nameBook.get(name) : new ArrayList<>(0);
    }

    //删除书籍
    public void deleteBook(String id) {
        Book book = getBookById(id);
        if (book != null) {
            bookList.remove(book);
            idBook.remove(book.getId());
            nameBook.get(book.getName()).remove(book);
        }
    }

    //加载本地数据
    public void loadData(String path) {
        File inFile = new File(path);
        if (inFile.exists()) {
            try (FileInputStream in = new FileInputStream(path);
                 ObjectInputStream inObj = new ObjectInputStream(in)) {
                List<Book> books = castList(inObj.readObject(), Book.class);
                if (books != null) {
                    bookList = books;
                    for (Book book : bookList) {
                        addBookIndex(book);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //保存数据到本地
    public void saveData(String path) {
        File outputFile = new File(path);
        if (!outputFile.exists()) {
            try {
                outputFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //覆盖写
        try (FileOutputStream out = new FileOutputStream(outputFile, false);
             ObjectOutputStream outObj = new ObjectOutputStream(out)) {
            outObj.writeObject(bookList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获取书籍信息表格
    public Object[][] getBookArray(List<Book> books) {
        Object[][] bookArray = new Object[books.size()][8];
        for (int i = 0; i < books.size(); i++) {
            bookArray[i][0] = books.get(i).getId();
            bookArray[i][1] = books.get(i).getName();
            bookArray[i][2] = books.get(i).getAuthor();
            bookArray[i][3] = books.get(i).getPublisher();
            bookArray[i][4] = books.get(i).getIsbn();
            bookArray[i][5] = books.get(i).getPublicationDate();
            bookArray[i][6] = books.get(i).getPages();
            bookArray[i][7] = books.get(i).getSummary();
        }
        return bookArray;
    }

    private void addBookIndex(Book book) {
        idBook.put(book.getId(), book);
        List<Book> nameBookList = nameBook.get(book.getName());
        if (nameBookList == null) {
            //若之前无重名书籍,新建一个list
            nameBookList = new ArrayList<>();
        }
        nameBookList.add(book);
        nameBook.put(book.getName(), nameBookList);
    }

    private static <T> List<T> castList(Object obj, Class<T> clazz) {
        List<T> result = new ArrayList<>();
        if (obj instanceof List<?>) {
            for (Object o : (List<?>) obj) {
                result.add(clazz.cast(o));
            }
            return result;
        }
        return null;
    }
}
